package servlet;

import dao.CartDAO;
import dao.UserDAO1;
import entity.Cart;
import org.bson.types.ObjectId;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author JPC
 * @version 1.0
 * @description: 添加购物车
 * @date 2024/7/16 17:14
 */
@WebServlet(name = "cartAdd",value = "/cart/add")
public class CartAddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        String num = req.getParameter("num");
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String username = req.getParameter("username");
        // 根据username查询id
        UserDAO1 dao = new UserDAO1();
        String userId = dao.findByName(username).getId();
        // 加入购物车
        CartDAO cartDAO = new CartDAO();
        Cart cart = new Cart(new ObjectId(userId), username, new ObjectId(id), name, Double.parseDouble(price), Integer.parseInt(num));
        cartDAO.insertCart(cart);
        System.out.println("id="+id+" num="+num+" name="+name+" price="+price+" username="+username + " userId="+userId);
        // 返回true
        resp.getWriter().write("true");
    }
}